const fileService = require('../service/file.service');
const momentService = require('../service/moment.service');
const fs = require('fs');
const { PICTURE_PATH } = require('../constants/file-path')
class MomentController {
    async create(ctx, next) {
    
        //获取userId
        const userId = ctx.user.id;
        const content = ctx.request.body.content;
        console.log(userId, content);

        //将数据插入数据库中
        const result = await momentService.create(userId, content);

        ctx.body = result;
    }; 

    async detail(ctx, next) {

        //获取数据
        const momentId = ctx.params.momentId;

        //根据id查询数据
        const result = await momentService.getMomentById(momentId);

        ctx.body = result;
    };

    async list(ctx, next) {
        const { offset, size } = ctx.query;
        
        const result = await momentService.getMomentList(offset, size);

        ctx.body = result;
    }

    async update(ctx, next) {
        const { momentId } = ctx.params;
        const { content } = ctx.request.body;
        const { id } = ctx.user;

        const result = await momentService.update(content, momentId);

        ctx.body = result;
    }

    async remove(ctx, next) {
        const { momentId } = ctx.params;
        const result = await momentService.remove(momentId);
        ctx.body = result;
    }

    async addLabels(ctx, next) {
        //获取标签和动态id
        const { labels } = ctx;
        const { momentId } = ctx.params;
        console.log(labels, momentId)
        
        //添加所有标签
        for (let label of labels) {
            //判断动态是否存在标签
            const isExist = await momentService.hasLabel(momentId, label.id);
            console.log(isExist)
            if (!isExist) {
                await momentService.addLabel(momentId, label.id);
            }
        }

        ctx.body = {
            code: 200,
            data: "给动态添加标签成功"
        };
    }

    async fileInfo(ctx, next) {
        const { filename } = ctx.params;
        const fileInfo = fileService.getFileByFilename(filename);

        const { type } = ctx.query;
        console.log(type)

        const types = ["small", "middle", "large"]; //手动选择照片尺寸
        console.log(filename)
        let a = types.some(item => {
            return item === type
        })
        console.log(a)
        let law = "";
        if (a) {
            console.log(filename, type)
            law = `${filename}-${type}`; 
            console.log(law)
        } else {
            law = filename;
        }

        ctx.response.set('content-type', fileInfo.mimetype);
        ctx.body = fs.createReadStream(`${PICTURE_PATH}/${law}`);

    }
}

module.exports = new MomentController();    